
package com.yesep.learn.mqtt.server.broker.handler.protocol;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yesep.learn.mqtt.protocol.IDisConnect;
import com.yesep.learn.mqtt.server.common.Constants;
import com.yesep.learn.mqtt.server.common.message.IDupPubRelMessageStoreService;
import com.yesep.learn.mqtt.server.common.message.IDupPublishMessageStoreService;
import com.yesep.learn.mqtt.server.common.session.ISessionStoreService;
import com.yesep.learn.mqtt.server.common.session.SessionStore;
import com.yesep.learn.mqtt.server.common.subscribe.ISubscribeStoreService;
import com.yesep.learn.mqtt.util.ChannelUtil;

import io.netty.channel.Channel;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.util.AttributeKey;

/**
   *    消息编号：14
 * @Description: DISCONNECT连接处理，断开连接
 */
@Service
public class DisConnect implements IDisConnect {

	private static final Logger LOGGER = LoggerFactory.getLogger(DisConnect.class);
	@Autowired
	private ISessionStoreService sessionStoreService;
	@Autowired
	private ISubscribeStoreService subscribeStoreService;
	@Autowired
	private IDupPublishMessageStoreService dupPublishMessageStoreService;
	@Autowired
	private IDupPubRelMessageStoreService dupPubRelMessageStoreService;

	public void process(Channel channel, MqttMessage msg) {
		String clientId =  ChannelUtil.getClientId(channel);
		SessionStore sessionStore = sessionStoreService.get(clientId);
		if (sessionStore.isCleanSession()) {
			subscribeStoreService.removeForClient(clientId);
			dupPublishMessageStoreService.removeByClient(clientId);
			dupPubRelMessageStoreService.removeByClient(clientId);
		}
		LOGGER.debug("DISCONNECT - clientId: {}, cleanSession: {}", clientId, sessionStore.isCleanSession());
		sessionStoreService.remove(clientId);
		channel.close();
	}

}
